package cn.wit.summit.chwan.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.adapters.RecommendV2Adapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.db.NetResultCacheTable;
import cn.wit.summit.chwan.models.dbmanager.NetResultCacheManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.request.GameLibraryV3Request;
import cn.wit.summit.chwan.models.response.GameLibraryV3Response;
import cn.wit.summit.chwan.models.response.IndexBeanV2Response;
import cn.wit.summit.chwan.models.response.IndexBeanV32Response;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.activity.SearchActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.DownloadViewStrokeV2Big;
import cn.wit.summit.chwan.widgets.ItemListPartView;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import io.supercharge.shimmerlayout.ShimmerLayout;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/9/27.
 */

public class GameLibraryV2Fragment extends BaseFragment {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.retryImg)
    ImageView retryImg;
    @Bind(R.id.retryText)
    TextView retryText;
    @Bind(R.id.notNetFl)
    FrameLayout notNetFl;
    @Bind(R.id.recommendTopWallet)
    RecommendTopWalletV2View recommendTopWallet;
    @Bind(R.id.recommendTopDownload)
    RecommendTopDownloadV2View recommendTopDownload;
    @Bind(R.id.recommendTopOneLl)
    LinearLayout recommendTopOneLl;
    @Bind(R.id.bar_title_tx)
    TextView barTitleTx;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.backSdv)
    SimpleDraweeView backSdv;
    @Bind(R.id.topTitle)
    RelativeLayout topTitle;
    @Bind(R.id.headerLl)
    LinearLayout headerLl;
    @Bind(R.id.shimmerLayout)
    ShimmerLayout shimmerLayout;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    private NetResultCacheTable table = null;

    private int pn = 1;
    private LinearLayoutManager layoutManager;
    private RecommendV2Adapter adapter;
    private List<RecommendV2Adapter.ViewBean> viewBeans = new ArrayList<>();

    private ControllerListener controllerListener;
    private Animatable mAnimatable;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_game_library_v2, null);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);

        barTitleTx.setText(getResources().getString(R.string.title_home));
        back.setImageResource(R.mipmap.ic_main_top_search);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        initListView();
        initData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        changeLoginStatus();
        changeTopStatus();
//        StatFactory.getInstance().sendVistPage(getActivity(), "Index", "Index");

        boolean isClick = PreferenceUtil.getBoolPreferences(getActivity(), PreferenceUtil.PRE_SEARCH_IS_CILICK);
        if (isClick) {
            back.setVisibility(View.VISIBLE);
            backSdv.setVisibility(View.GONE);
            handler.removeMessages(1);
        } else {
            if (controllerListener==null) {
                controllerListener = new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(
                            String id,
                            @Nullable ImageInfo imageInfo,
                            @Nullable Animatable anim) {
                        mAnimatable = anim;
                        handler.removeMessages(1);
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                };
            }

            back.setVisibility(View.GONE);
            backSdv.setVisibility(View.VISIBLE);
            Uri uri = Uri.parse("asset:///aaa.gif");
            DraweeController draweeController = Fresco.newDraweeControllerBuilder().setUri(uri)
//                    .setAutoPlayAnimations(true) // 设置加载图片完成后是否直接进行播放
                    .setControllerListener(controllerListener)
                    .build();
            backSdv.setController(draweeController);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (mAnimatable!=null) {
                        mAnimatable.stop();
                        mAnimatable.start();
                        handler.removeMessages(1);
                        Message mess = new Message();
                        mess.what = 1;
                        handler.sendMessageDelayed(mess, 2500);
                    }
                    break;
            }
        }
    };

    private void initListView() {
        layoutManager = new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };

        adapter = new RecommendV2Adapter(getActivity(), viewBeans);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getIndexDataForFirst();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getIndexData();
            }
        });
    }

    private void getIndexDataForFirst() {
        refreshLayout.setEnableLoadMore(true);
        pn = 1;
        getIndexData();
    }

    private void initData() {
        try {
            showSkeleton();
            Map<String, String> tempMap = new HashMap<>();
            tempMap.put("pn", "1");
            String requestStr = new Gson().toJson(tempMap);
            table = NetResultCacheManager.getInstance().getDataByUrl(RpcConstant.forumRootUrl + RpcConstant.homePageV3_2, requestStr);
            if (table != null && !StringUtils.isEmpty(table.getResponseStr())) {
                String data = table.getResponseStr();
                ResponseBase<GameLibraryV3Response> temp = fromJsonObject(data, GameLibraryV3Response.class);
//                initTabsView(temp.getData_info());
                hideSkeleton();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getIndexData();
    }

    public <T> ResponseBase<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new NetCallBack.ParameterizedTypeImpl(ResponseBase.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        changeLoginStatus();
        changeTopStatus();
        if (!hidden) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getUserinfo();
                }
            }, 500);
        }
    }

    private void getIndexData() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            int uId = 0;
            AccountBean accountBean = AccountUtil.getInstance().getAccountData();
            if (accountBean != null) {
                uId = AccountUtil.getInstance().getUid();
            }
            GameLibraryV3Request request = retrofitManager.gameLibraryV3Request(uId, pn);
            api.gameLibraryV3_2(request).enqueue(new MyCallback<ResponseBase<IndexBeanV32Response>>() {
                @Override
                public void onSuccess(ResponseBase<IndexBeanV32Response> model) {
                    if (pn == 1) {
                        Gson gson = new Gson();
                        Map<String, String> tempMap = new HashMap<>();
                        tempMap.put("pn", pn + "");
                        String requestStr = gson.toJson(tempMap);
                        String retStr = gson.toJson(model);
                        String retUrl = RpcConstant.forumRootUrl + RpcConstant.homePageV3_2;
                        LogUtils.e("retUrl:" + retUrl + "\nrequestStr:" + requestStr + "\nretStr:" + retStr);
                        NetResultCacheManager.getInstance().insertData(retUrl, requestStr, retStr);
                    }

                    IndexBeanV32Response data = model.getData_info();
                    updataUi(data);
                    hideSkeleton();
                }

                @Override
                public void onFailure(int code, String msg) {
                    showToast(msg);
                    try {
                        refreshLayout.finishLoadMore();
                        if (viewBeans.size() == 0) {
                            if (code == -3) {
                                notNetFl.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                            }
                            refreshLayout.finishRefresh();
                            hideSkeleton();
                        } else {
                            refreshLayout.finishRefresh();
                            hideSkeleton();
                        }
                    } catch (Exception e) {
                        if (viewBeans.size() == 0) {
                            if (code == -3) {
                                notNetFl.setVisibility(View.VISIBLE);
                            }
                            hideSkeleton();
                        } else {
                            hideSkeleton();
                        }
                        e.printStackTrace();
                    }
                }
            });
        } else {
            notNetFl.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
            retryImg.setImageResource(R.mipmap.ic_not_net);
            retryText.setText("网络异常，点击屏幕重新加载");
        }
    }

    private void updataUi(IndexBeanV32Response data) {
        if (data == null) {
            return;
        } else {
            if (notNetFl != null)
                notNetFl.setVisibility(View.GONE);
            if (refreshLayout != null)
                refreshLayout.setVisibility(View.VISIBLE);
        }
        if (pn == 1) {
            viewBeans.clear();
            adapter.clearTempData();

            List<JumpBaseBean> bannerTopList = data.getTop_banner_info();
            if (bannerTopList!=null && bannerTopList.size()>0) {
                if (bannerTopList.get(0).getGame_list()!=null && bannerTopList.get(0).getGame_list().size()>0) {
                    RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME, bannerTopList.get(0));
                    viewBeans.add(viewBean);
                }
            }

            viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP_HEIGHT2));
            viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP_HEIGHT5));
//            viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP));
        }

//        RecommendV2Adapter.ViewBean lineView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_LINE_22);

        JumpBaseBean banner = data.getRecommend_info().getRecommend_banner();
        if (banner != null && banner.getGame_list() != null && banner.getGame_list().size() > 0) {
//            if (viewBeans.size() > 0)
//                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME_V2, banner);
            viewBeans.add(viewBean);
        }

        //分页数据
        List<JumpBaseBean> bannerList = data.getRecommend_info().getRecommend_banner_list();
        for (int i = 0; bannerList != null && i < bannerList.size(); i++) {
            JumpBaseBean tempBanner = bannerList.get(i);
            if (tempBanner.getGame_list() != null && tempBanner.getGame_list().size() > 0) {
//                if (viewBeans.size() > 0)
//                    viewBeans.add(lineView);
                if (tempBanner != null && tempBanner.getGame_list() != null && tempBanner.getGame_list().size() > 0) {
                    RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME_V2, tempBanner);
                    viewBeans.add(viewBean);
                }
            }
        }

        JumpBaseBean dailyNew = data.getRecommend_info().getRecommend_edn();
        if (dailyNew != null && dailyNew.getGame_list() != null && dailyNew.getGame_list().size() > 0) {
//            if (viewBeans.size() > 0)
//                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, dailyNew);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_DAILY_NEW, dailyNew);
            viewBeans.add(viewBean);
        }

        JumpBaseBean gameStarter = data.getRecommend_info().getRecommend_tf();
        if (gameStarter != null && gameStarter.getGame_list() != null && gameStarter.getGame_list().size() > 0) {
//            if (viewBeans.size() > 0)
//                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, gameStarter);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME_V2, gameStarter);
            viewBeans.add(viewBean);
        }

        JumpBaseBean greatCrack = data.getRecommend_info().getRecommend_game_list_v1();
        if (greatCrack != null && greatCrack.getGame_list() != null && greatCrack.getGame_list().size() > 0) {
//            if (viewBeans.size() > 0)
//                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GREAT_CRACK, greatCrack);
            viewBeans.add(viewBean);
        }

        JumpBaseBean gameHot = data.getRecommend_info().getNet_hot_game();
        if (gameHot != null && gameHot.getGame_list() != null && gameHot.getGame_list().size() > 0) {
//            if (viewBeans.size() > 0)
//                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, gameHot);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_HOT, gameHot);
            viewBeans.add(viewBean);
        }

        JumpBaseBean greatCrackV2 = data.getRecommend_info().getRecommend_game_list_v2();
        if (greatCrackV2 != null && greatCrackV2.getGame_list() != null && greatCrackV2.getGame_list().size() > 0) {
//            if (viewBeans.size() > 0)
//                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GREAT_CRACK, greatCrackV2);
            viewBeans.add(viewBean);
        }

        JumpBaseBean MediaTest = data.getRecommend_info().getMedia_test();
        if (MediaTest != null && MediaTest.getGame_list() != null && MediaTest.getGame_list().size() > 0) {
//            if (viewBeans.size() > 0)
//                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, MediaTest);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_HOT, MediaTest);
            viewBeans.add(viewBean);
        }

        JumpBaseBean greatCrackV3 = data.getRecommend_info().getRecommend_game_list_v3();
        if (greatCrackV3 != null && greatCrackV3.getGame_list() != null && greatCrackV3.getGame_list().size() > 0) {
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, greatCrackV3, true);
            viewBeans.add(titleView);
            for (int i=0;i<greatCrackV3.getGame_list().size();i++) {
                GameListBaseBean temp = greatCrackV3.getGame_list().get(i);
                RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_LIST, temp);
                viewBeans.add(viewBean);
            }
        }

        adapter.notifyDataSetChanged();
        if (refreshLayout != null) {
            if (pn != 1 && (data == null || data.getRecommend_info().getRecommend_banner_list() == null
                    || data.getRecommend_info().getRecommend_banner_list().size() == 0)) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                if (pn == 1)
                    refreshLayout.finishRefresh();
                else
                    refreshLayout.finishLoadMore();
                pn += 1;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        recommendTopDownload.setTotalDownloadNum();//设置下载数

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));

            DownloadViewStrokeV2Big downView = view.findViewById(R.id.itemCrackGameBt);
            if (downView != null) {
                downView.updateButn(table);
            } else {
                ItemListView itemView = view.findViewById(R.id.listItem);
                if (itemView == null) {
                    return;
                }
                DownloadViewStroke downView2 = itemView.getDownView();
                downView2.updateButn(table);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.notNetFl, R.id.back, R.id.backSdv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backSdv:
                PreferenceUtil.saveBoolPreference(getActivity(), PreferenceUtil.PRE_SEARCH_IS_CILICK, true);
            case R.id.back:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
                break;
            case R.id.notNetFl:
                if (table == null)
                    showSkeleton();
                notNetFl.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
                refreshLayout.autoRefresh();
                getIndexData();
                break;
        }
    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                            }
                            ToastUtils.getInstance(getActivity()).showToastSystem(msg);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void changeLoginStatus() {
        recommendTopWallet.initTotalWalletNum();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EnergyEvent energyEvent) {
        if (recommendTopWallet != null) {
            recommendTopWallet.initTotalWalletNum();
        }
    }

    private void changeTopStatus() {
        try {
            if (recommendTopDownload != null) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (recommendTopDownload != null) {
                            recommendTopDownload.setTotalDownloadNum();
                        }
                    }
                }, 200);
            }
        } catch (Exception e) {
        }
    }

    private void showSkeleton() {
        shimmerLayout.setVisibility(View.VISIBLE);
        refreshLayout.setVisibility(View.GONE);
        notNetFl.setVisibility(View.GONE);
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        shimmerLayout.startShimmerAnimation();
    }

    private void hideSkeleton() {
        notNetFl.setVisibility(View.GONE);
        shimmerLayout.setVisibility(View.GONE);
        refreshLayout.setVisibility(View.VISIBLE);
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        shimmerLayout.stopShimmerAnimation();
    }

    private int mShimmerColor;
    private boolean mShimmer = true;
    private int mShimmerDuration = 1200;
    private int mShimmerAngle = 20;
    View innerView;

    private void initSkeleton() {
        mShimmerColor = ContextCompat.getColor(getActivity(), R.color.shimmer_color);

        shimmerLayout.setShimmerColor(mShimmerColor);
        shimmerLayout.setShimmerAngle(mShimmerAngle);
        shimmerLayout.setShimmerAnimationDuration(mShimmerDuration);

        innerView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_game_lib_skeleton, shimmerLayout, false);
        shimmerLayout.addView(innerView);
        shimmerLayout.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                if (shimmerLayout!=null) {
                    shimmerLayout.startShimmerAnimation();
                }
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                if (shimmerLayout!=null) {
                    shimmerLayout.stopShimmerAnimation();
                }
            }
        });
    }
}
